-- ========================================================
-- @File	: model.lua
-- @Brief	: 模型导基类
-- @Author	: Leo Zhao
-- @Date	: 2016-05-05
-- ========================================================
model = model or {}

-- 声明一个model
function model.new()
	if model.conn then return inherit(model) end;

	assert(
		_CONF.database and _CONF.database.host and _CONF.database.storage, 
		'You MUST define database in app/config.lua');

	local c = vendor('mysql').config('mariadb');	
	model.conn = c.connect(
		_CONF.database.host, 
		_CONF.database.user or 'root', 
		_CONF.database.pswd or nil, 
		_CONF.database.storage, nil, 
		_CONF.database.port or 3306);
	
	return inherit(model);
end

-- 取出一个模型的定义
function model.get(name)
	return require('app.models.' .. name);
end

-- Query，用于查找
function model.query(sql)
	assert(model.conn, "Please use model.new() instead of model itself.");
	model.conn:query(sql);

	local res = model.conn:store_result();
	local tb = {};
	for idx, data in res:rows('a') do
		table.insert(tb, data);
	end

	return tb;
end

-- Update，用于更新，删除，插入。返回status(INT)
function model.update(sql)
	assert(model.conn, "Please use model.new() instead of model itself.");
	model.conn:query(sql);
	return model.conn:affected_rows();
end

